package core

import (
	"dgo/goutils/utils"
	"fmt"
	"gitee.com/ymofen/supervalue"
)

/***
  设置FatalFile文件, 该插件只能有一个
*/

type PlugFatalFile struct {
	plugId string
}

var (
	fatal_log_file        string         = ""
	PlugFatalFileInstance *PlugFatalFile = nil
)

/*
*

	{
	   "filename":"$approot$/log/fatal.log",
	}
*/
func (this *PlugFatalFile) ReloadConf(conf *wrapper.SuperValue) error {
	if PlugFatalFileInstance == nil {
		PlugFatalFileInstance = this
	}
	if PlugFatalFileInstance != this {
		return fmt.Errorf("PlugFatalFile插件只能创建一个")
	}

	filename := conf.StringByName("filename", "NONE")
	if filename != "NONE" {
		filename = ReplacePlaceholderForFileName(filename)
		if fatal_log_file != filename {
			fatal_log_file = filename
			utils.DeferFatalRec()
			if len(fatal_log_file) > 0 {
				utils.ForceCreateFilePath(fatal_log_file)
				utils.SetFatalRec(fatal_log_file)
				utils.Log.InfoTypef("STATE", "开启FatalLog:%s", fatal_log_file)
			} else {
				utils.Log.InfoTypef("STATE", "关闭FatalLog")
			}
		}
	}

	return nil

}

func (this *PlugFatalFile) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {
		utils.DeferFatalRec()
	}
	return
}

func CreatePlugFatalFileFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &PlugFatalFile{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.plugId = str
		}
	}
	rval = obj
	return
}
